package MeteoCal.utility;

import MeteoCal.bean.EventBean;
import MeteoCal.entity.User;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
 
/**
 *
 * @authors Guttadoro, Iommazzo, Saullo
 */  
@FacesConverter("userConverter")
public class UserConverter implements Converter {
 
    public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
        if(value != null && value.trim().length() > 0) {
            try {
                FacesContext context = FacesContext.getCurrentInstance();
                EventBean bean = context.getApplication().evaluateExpressionGet(context, "#{eventBean}", EventBean.class);
                List<User> service = bean.getUsers();
                //List<User> service = ((EventBean) fc.getExternalContext().getApplicationMap().get("eventBean")).getUsers();
                for (User serv : service)
                    if (serv.getEmail().equals(value))
                        return serv;
            } catch(NumberFormatException e) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid user."));
            }
        }
        return null;
    }
 
    public String getAsString(FacesContext fc, UIComponent uic, Object object) {
        if(object != null) {
            return ((User) object).getEmail();
        }
        else {
            return null;
        }
    }
}   